import threading
import time

from PySide2 import QtWidgets
from PySide2.QtCore import Qt
from PySide2.QtGui import QStandardItemModel, QStandardItem, QIcon

from robotController import share
from robotController.elementUI.freezeTableWidget import masking_element
from robotController.util import fileSelect
from robotController.binding import original_share
from PySide2.QtWidgets import QTableWidgetItem, QPushButton, QHBoxLayout, QWidget, QMessageBox, QTableView, QHeaderView, \
    QApplication

import json
import requests

from robotController.util.TableWidgetUtil import TableWidgetUtil
from robotController.util.requestUtil import requestUtil

class bind:
    def __init__(self):

        self.ui = share.SI.main.ui

    def incident(self):

        # 绑定上传按钮事件
        self.ui.original_submit_button.clicked.connect(lambda : self.submit_file())
        self.ui.original_submit_button.setIcon(QIcon("./static/img/提交.png"))
        # 绑定查询按钮
        self.ui.origin_select_button.clicked.connect(lambda : self.findAll())
        self.ui.origin_select_button.setIcon(QIcon("./static/img/查询.png"))


    # 查询头源数据列表
    def findAll(self):
        # 清空数据
        self.dataList = []
        name = self.ui.origin_select_lineEdit.text() if self.ui.origin_select_lineEdit.text() != "" else "None"
        # 拉取源数据头列表
        requests.encoding = 'utf-8'
        dataMap = requestUtil("/original/" + name,"GET").dataMap
        for index,item in enumerate(dataMap['data']):
            item["buttons"] = self.buttonForRow(item["id"],item["name"])

        self.dataList = dataMap['data']

        # 将数据渲染至列表中
        self.dataList_renderer()


    # 将数据渲染至列表中
    def dataList_renderer(self):
        # 设置表头颜色及显示
        TableWidgetUtil().head_color_show(self.ui.original_tableWidget)
        # 准备映表头射组
        head = [{'key':"年度","value":"version"},{'key':"期间","value":"period"},{'key':"编码","value":"code"},{'key':"上传时间","value":"uploadingTime"},{'key':"上传单位","value":"oname"},{'key':"名称","value":"name"},{'key':"操作","value":"buttons"}]
        TableWidgetUtil().render(self.ui.original_tableWidget,self.dataList,head)

    # 列表内添加按钮
    def buttonForRow(self,id,name):
        widget=QWidget()
        # 删除
        deleteBtn = QPushButton('删除')
        deleteBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:red;}
                                     
                                    QPushButton:hover{
                                    	color: red;
                                    	text-decoration:underline;
                                    }''')

        # 查看
        alterBtn = QPushButton('查看')
        alterBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:#192D9E;
                                    }
                                     
                                    QPushButton:hover{
                                    	color: #192D9E;
                                    	text-decoration:underline;
                                    }''')

        alterBtn.clicked.connect(lambda : self.alter_fun(str(id),name))

        deleteBtn.clicked.connect(lambda : self.del_fun(str(id)))

        hLayout = QHBoxLayout()
        hLayout.addWidget(alterBtn)
        hLayout.addWidget(deleteBtn)
        hLayout.setContentsMargins(5,2,5,2)
        widget.setLayout(hLayout)
        return widget

    # 删除对应
    def del_fun(self,id):

        A = QMessageBox.question(self.ui.template_tableWidget,'确认','是否删除该表?',QMessageBox.Yes | QMessageBox.No)
        if A == QMessageBox.No:
            return

        dataMap = requestUtil("/original/delete/" + id,"DELETE").dataMap
        try:
            if dataMap["flag"] == True:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget ,"信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findAll()

        except:
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget ,"信息提示框", dataMap["error"])

    # 查询源数据体
    def get_original_data(self,id,model):
        # 获取原表 体数据
        dataMap = requestUtil("/original/findByPid/" + str(id),"GET").dataMap
        dataList = [row["data"] for index,row in enumerate(dataMap["data"])]
        # 存储行及id的倒排索引列表
        original_share.RD.idList = [row["id"] for index,row in enumerate(dataMap["data"])]
        for index,item in enumerate(dataList):
            item = json.loads(item, strict=False)
            for col,itemcol in enumerate(item):
                model.setItem(index, col, QStandardItem(itemcol))
                # 将可转换为数字的文字转为数字
                if col != 0 and  self.is_number(itemcol.replace(",","")):
                    model.item(index, col).setTextAlignment(Qt.AlignRight|Qt.AlignVCenter)

    # 修改源数据
    def alter_fun(self,id,name):
        masking = masking_element()
        masking.mpShadeWindow.show()
        QApplication.processEvents()
        # 准备数据
        model = QStandardItemModel()
        # 获取源列表表格
        original_tableView = self.ui.original_widget.findChild(QTableView,"original_tableView")

        # 清空original_tableView表格
        original_tableView.set_model(model)

        if '科目余额' in name:
            self.get_original_data(id,model)
            original_tableView.set_model(model)
            # 缓存id
            original_share.RD.id = id
            self.ui.stackedWidget.setCurrentIndex(1)
            # 合并表头
            self.merge_header()

        elif '现金流量' in name:
            original_tableView_1 = self.ui.original_tableView_1
            original_tableView_1.setRowCount(0)
            # 准备数据
            dataMap = requestUtil("/original/findByPid/" + str(id),"GET").dataMap
            dataList = [row["data"] for index,row in enumerate(dataMap["data"])]
            # 设置表头
            head_data = json.loads(dataList[0], strict=False)
            original_tableView_1.setRowCount(len(dataList))
            original_tableView_1.setColumnCount(len(head_data))
            original_tableView_1.setHorizontalHeaderLabels(head_data)
            TableWidgetUtil().head_color_show(original_tableView_1)
            original_tableView_1.horizontalHeader().setDefaultSectionSize(200)
            original_tableView_1.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)
            # 渲染主体数据
            for rowindex,row in enumerate(dataList[1:]):
                row = json.loads(row, strict=False)
                for colindex,col in enumerate(row):
                    original_tableView_1.setItem(rowindex, colindex, QTableWidgetItem(str(col)))
                    # 将可转换为数字的文字转为数字
                    if self.is_number(col.replace(",","")):
                        # 内容靠右
                        original_tableView_1.item(rowindex, colindex).setTextAlignment(Qt.AnchorRight|Qt.AlignVCenter)
                    else:
                        # 内容靠左
                        original_tableView_1.item(rowindex, colindex).setTextAlignment(Qt.AnchorLeft|Qt.AlignVCenter)
            self.ui.stackedWidget.setCurrentIndex(2)
        masking.mpShadeWindow.hide()


    # 判断字符串是否是数字
    def is_number(self,target_str):
        try:
            float(target_str)
            return True
        except:
            pass
        if target_str.isnumeric():
            return True
        return False

    # 合并表头
    def merge_header(self):
        # 合并表头
        original_tableView = self.ui.original_widget.findChild(QTableView,"original_tableView")

        # 获取表头列数
        original_model = original_tableView.horizontalView.model()
        columnCount = original_model.columnCount()
        # 有效单元格记录（每出现一个新的头记录一次）
        valid_cell_data = -1
        valid_cell_index = -1
        # 纵向合并记录
        vertical_merger = False
        # 遍历获取合并区间
        for column in range(columnCount):
            # 表头文字居中
            original_tableView.horizontalView.model().item(0, column).setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter);
            original_tableView.horizontalView.model().item(1, column).setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter);


            indexOne = original_model.index(0, column)      #第一行索引
            indexTwo = original_model.index(1, column)      #第二行索引
            dataOne = str(original_model.data(indexOne))       #第一行值
            dataTwo = str(original_model.data(indexTwo))       #第二行值
            if (dataOne != valid_cell_data and dataOne != ""):          # 该单元格内容有效

                # 若有效记录不为-1则记录上次合并
                if valid_cell_index != -1:
                    if vertical_merger:         #合并包含第二列
                        original_tableView.horizontalView.setSpan(0,valid_cell_index,2,column-valid_cell_index)
                        original_tableView.BRTableView.setSpan(0,valid_cell_index,2,column-valid_cell_index)
                    else:                       #合并不包含第二列
                        original_tableView.horizontalView.setSpan(0,valid_cell_index,1,column-valid_cell_index)
                        original_tableView.BRTableView.setSpan(0,valid_cell_index,1,column-valid_cell_index)
                    vertical_merger = False

                if dataTwo == dataOne or dataTwo == "":         #该次合并包含第二列
                    vertical_merger = True

                valid_cell_index = column
                valid_cell_data = dataOne

        # 进行最后一次合并
        if vertical_merger:         #合并包含第二列
            original_tableView.horizontalView.setSpan(0,valid_cell_index,2,columnCount-valid_cell_index)
            original_tableView.BRTableView.setSpan(0,valid_cell_index,2,columnCount-valid_cell_index)
        else:                       #合并不包含第二列
            original_tableView.horizontalView.setSpan(0,valid_cell_index,1,columnCount-valid_cell_index)
            original_tableView.BRTableView.setSpan(0,valid_cell_index,1,columnCount-valid_cell_index)


    def submit_file(self):
        # 选择源数据位置
        data_address = fileSelect.file_address()
        try:
            file_name = data_address[fileSelect.find_last(data_address,"/"):]
            url = share.RURL.backendUrl+"/original/originalImport"
            files = {'file': (file_name, open(data_address, 'rb'))}
            result = requests.request(method="POST", url=url,files=files, verify=False, headers=share.token.headers)
            dataMap = json.loads(result.text)
            if dataMap["flag"]:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget ,"信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findAll()
                # 将数据渲染至列表中
                self.dataList_renderer()
        except:
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget ,"信息提示框", "提交源数据失败")

    # 同步按钮
    def synchronization_button(self):
        self.alter_data()
        # 核心功能代码就两行，可以加到需要的地方
        msg_box = QMessageBox(QMessageBox.Warning, '提示', '同步成功')
        msg_box.exec_()

    # 修改数据
    def alter_data(self):
        # 记录已经更改的数据
        final_data = []

        for item in share.bind.processing_dataList:
            # 当前修改的数据行
            dataitem = original_share.RD.dataMap['data'][item[0]+2]['data']
            # 待修改数据转数组
            dataup = json.loads(dataitem)
            dataup[item[1]] = str(item[2])

            dataStr = json.dumps(dataup, ensure_ascii=False)

            # 将修改后的数据赋值
            original_share.RD.dataMap['data'][item[0]+2]['data'] = dataStr
            final_data.append(original_share.RD.dataMap['data'][item[0]+2])

        url = share.RURL.backendUrl + "/original"
        requests.encoding = 'utf-8'
        requests.request(method="PUT", url=url,json=final_data, headers=share.token.headers)

        share.bind.processing_dataList = []

        # 重新拉取数据
        self.find_original_data_All(original_share.RD.id)
        # 渲染数据
        self.original_data_renderer()

    def find_original_data_All(self, id):
        url = share.RURL.backendUrl + "/original/findByPid/" + id
        requests.encoding = 'utf-8'
        result = requests.request(method="GET", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)
        self.dataMap = dataMap
        original_share.RD.dataMap = dataMap
        # 源数据
        data = dataMap['data']
        dataHead = data[:2]
        self.dataList = []
        self.data = []
        # 表头处理赋值
        for index in range(len(dataHead)):
            data_Head_item = json.loads(dataHead[index]["data"])
            self.dataList.append(data_Head_item)

        for index in range(len(data)):
            data_item = json.loads(data[index]["data"])
            self.data.append(data_item)

    #    主体数据渲染
    def original_data_renderer(self):
        original_data = self.data[2:]
        # 设置主体数据条数
        self.ui.tableWidget.setRowCount(len(original_data));
        for y in range(len(original_data)):
            for x in range(len(original_data[y])):
                if original_data[y][x] != '':
                    self.ui.tableWidget.setItem(y, x, QTableWidgetItem(original_data[y][x]))
                else:
                    self.ui.tableWidget.setItem(y, x, QTableWidgetItem(''))